﻿using fuzhu;
using LH.Models.APAR;
using LH.U8API.Bus; 
using Org.BouncyCastle.Asn1.Ocsp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.GL;
using LH.Model.SA;
using ZDEntity;
using XXX.Models.AS;
using System.Diagnostics.Eventing.Reader;
using XXX.Models.WDFT;
using System.DirectoryServices.ActiveDirectory;
using System.Reflection;
using System.Security.Cryptography;
using System.Xml.Linq;
using MySqlConnector;
using XXX.Models.XXXEntities;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using System.Security.Policy;


namespace Yonyou.U8.BO
{
    //发货单
    public class DispatchlistVM_KX : SA_DispatchList
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public static string cDatabase = "";

        public DispatchlistVM_KX(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

       

        public  RetModel2 AddVerify()
        {
            try
            {
               

              
                string xmlconfig = XmlOperation.GetConfigXML();

                
                if (!DispatchlistCO.AddVerifySA_DispatchList(this, xmlconfig, out string err, out string id, out string ccode))
                {
                    return DBService.ReErrObject("新增失败：" + err);
                }
                //else
                //{

                //    if (!SO_SOCO.OperateSaleOrder(id, "verify", out err))
                //    {
                //        //审核失败，需要删除数据
                //        SO_SOCO.OperateSaleOrder(id, "delete", out _);
                //        return DBService.ReErrObject("审核失败：" + err); ;
                //    }
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }

        /// <summary>
        /// 销售订单 弃审并删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 UnverifyDelete()
        {
            try
            {
                string ID = "";
                if (!Exists(ref ID))
                {
                    return DBService.ReOKObject("当前销售订单号已删除");
                }
                
                if (!SO_SOCO.OperateSaleOrder(ID, xmlConfig, "unverify,delete", out string err))
                {
                    return DBService.ReErrObject("弃审失败：" + err);
                }
                //else
                //{
                //    if (!SO_SOCO.OperateSaleOrder(ID, "delete", out err))
                //    {
                //        //删除失败,重新审核，保持原样
                //        SO_SOCO.OperateSaleOrder(ID, "verify", out _);
                //        return DBService.ReErrObject("删除失败：" + err);
                //    }
                return DBService.ReOKObject(head.csocode + "删除完成");
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }


        

        /// <summary>
        /// 完善发货单信息,处理客户，金额，税率，辅助计量单位
        /// </summary>
        /// <returns></returns>
        public string GetWDFTInfo()
        {
            if (head == null)
            {
                return "Error: 没有数据";
            }
            if (bodies == null)
            {
                return "Error: 没有表体数据";
            }
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                //取销售订单表头信息
                WMS_GetSource source = db.Queryable<SO_SOMain>().Where(x=>x.cSOCode==head.csocode)
                    .Select(x=>new WMS_GetSource
                    {
                        cPTCode = x.cSTCode,
                        cCusCode = x.cCusCode,
                        cDefine1 = x.cCusName,
                        cexch_name = x.cexch_name,
                        iExchRate = x.iExchRate, 
                        cDepCode = x.cDepCode,
                        cPersonCode = x.cPersonCode, 
                        cBusType = x.cBusType,
                        iTaxRate = (decimal?)x.iTaxRate, 
                    }).First();

                if (source != null)
                {
                    head.cstcode = source.cPTCode;
                    head.cdepcode = source.cDepCode;
                    head.cpersoncode = source.cPersonCode;
                    head.cbustype = source.cBusType;
                    head.ccuscode = source.cCusCode;
                    head.ccusname = source.cDefine1;
                    head.cinvoicecusname = source.cDefine1;
                    head.cinvoicecompany = source.cCusCode;
                    head.ccreditcuscode = source.cCusCode;
                    head.cexch_name  = source.cexch_name;
                    head.iexchrate =DbHelper.GetDbString(source.iExchRate);
                    head.itaxrate = DbHelper.GetDbString( source.iTaxRate);
                    //根据客户具体设置
                    head.bsaleoutcreatebill = "0";

                }
                else
                {
                    return "Error: U8内查找不到此销售订单号"+head.csocode;
                }

                //取销售订单信息

                for (int i = 0; i < bodies.Count; i++)
                {
                    
                    WMS_GetSource sourcerow = db.Queryable<SO_SOMain>()
                               .InnerJoin<SO_SODetails>((a, b) => a.ID == b.ID &&  a.cSOCode==head.csocode && b.cDefine33 == bodies[i].cdefine32)
                               .Select((a, b) => new WMS_GetSource
                               {  
                                   cInvCode = b.cInvCode,
                                   cUnitID = b.cUnitID,
                                   iChangeRate = b.iInvExchRate,
                                   iQuantity = (decimal)b.iQuantity,
                                   iNum = b.iNum,
                                   cbMemo = b.cMemo,
                                   iTaxRate  = b.iTaxRate,
                                   bsaleprice = b.bsaleprice,
                                   iOriCost = b.iUnitPrice,
                                   iOriTaxCost = b.iTaxUnitPrice,
                                   iOriMoney = b.iMoney,
                                   iOriTaxPrice = b.iTax,
                                   iOriSum = b.iSum,
                                   iSum = b.iNatSum,
                                   iMoney = b.iNatMoney,
                                   iTax =b.iNatTax,
                                   iCost  = b.iNatUnitPrice, 
                                   iSosid = b.iSOsID, 
                                   cItem_class = b.cItem_class,
                                   cItemCode = b.cItemCode,
                                   cItemName = b.cItemName ,
                                   cordercode  = a.cSOCode,
                                   isorowno = b.iRowNo

                               }).First();
                    if (sourcerow == null)
                    {
                        return string.Format("订单单bid关联不到销售订单：{0}", bodies[i].cdefine32);
                    }
                    else
                    {
                        bodies[i].cinvcode = sourcerow.cInvCode;
                        bodies[i].cunitid =  sourcerow.cUnitID;
                        bodies[i].iinvexchrate = DbHelper.GetDbString(sourcerow.iChangeRate);
                        bodies[i].itaxrate = DbHelper.GetDbString(sourcerow.iTaxRate);
                        bodies[i].irowno = (i + 1).ToString();
                        bodies[i].isosid = DbHelper.GetDbString(sourcerow.iSosid);
                        bodies[i].cordercode =  sourcerow.cordercode;
                        bodies[i].iorderrowno = DbHelper.GetDbString(sourcerow.isorowno);
                        bodies[i].idiscount = "0";
                        bodies[i].kl = "100";
                        bodies[i].kl2 = "100";
                        if (sourcerow.bsaleprice == true)
                        {
                            bodies[i].bsaleprice = "1";
                        }
                        else
                        {
                            bodies[i].bsaleprice = "0";
                        }

                        bodies[i].bgift = "0";
                        //如果发货数量= 销售订单数量，直接取销售订单的单价和金额
                        if (DbHelper.GetDbdecimal(bodies[i].iquantity) == sourcerow.iQuantity)
                        {
                            bodies[i].inum = DbHelper.GetDbString(sourcerow.iNum);
                            bodies[i].itaxunitprice = DbHelper.GetDbString(sourcerow.iOriTaxCost);
                            bodies[i].iunitprice = DbHelper.GetDbString(sourcerow.iOriCost);
                            bodies[i].imoney = DbHelper.GetDbString(sourcerow.iOriMoney);
                            bodies[i].isum = DbHelper.GetDbString(sourcerow.iOriSum);
                            bodies[i].itax = DbHelper.GetDbString(sourcerow.iOriTaxPrice);
                            bodies[i].inatunitprice= DbHelper.GetDbString(sourcerow.iOriTaxPrice);
                            bodies[i].inatmoney = DbHelper.GetDbString(sourcerow.iCost);
                            bodies[i].inattax = DbHelper.GetDbString(sourcerow.iTax);
                            bodies[i].inatsum = DbHelper.GetDbString(sourcerow.iSum);
                        }
                        else
                        {
                            #region 处理金额： 根据含税单价反算单价和无税单价
                            bodies[i].itaxunitprice = DbHelper.GetDbString(sourcerow.iOriTaxCost);
                            decimal dOriSum = Math.Round(DbHelper.GetDbdecimal(bodies[i].iquantity)* DbHelper.GetDbdecimal(sourcerow.iOriTaxCost),2);  //原币含税金额
                            bodies[i].iquotedprice = bodies[i].itaxunitprice;
                            decimal dOriMoney = Math.Round(DbHelper.GetDbdecimal((dOriSum / (1 + DbHelper.GetDbdecimal(bodies[i].itaxrate) / 100))),2);  //不含税金额
                            decimal dOriTax = dOriSum - dOriMoney;  //原币税额
                            bodies[i].isum = DbHelper.GetDbString(dOriSum);
                            bodies[i].imoney = DbHelper.GetDbString(dOriMoney);
                            bodies[i].itax = DbHelper.GetDbString(dOriTax);
                            bodies[i].iunitprice = DbHelper.GetDbString(dOriMoney / DbHelper.GetDbdecimal(bodies[i].iquantity));
                            decimal dSum = dOriSum * DbHelper.GetDbdecimal(head.iexchrate);
                            decimal dMoney = dOriMoney * DbHelper.GetDbdecimal(head.iexchrate);
                            decimal dTax = dSum - dMoney;  //原币税额 
                            bodies[i].inatsum = DbHelper.GetDbString(dSum);
                            bodies[i].inatmoney = DbHelper.GetDbString(dMoney);
                            bodies[i].inattax = DbHelper.GetDbString(dTax);
                            bodies[i].inatunitprice = DbHelper.GetDbString(dMoney / DbHelper.GetDbdecimal(bodies[i].iquantity)); 
                          
                            #endregion
                        }
                    }
                    InvProperty invProperty = new InventoryVM().GetInvProperty(bodies[i].cinvcode, "", "");
                    if (invProperty == null)
                    {
                        return string.Format("第{0}行订单物料和{1}不存在", (i + 1).ToString(), bodies[i].cinvcode);
                    }
                    else
                    {
                        bodies[i].cgroupcode = invProperty.cGroupCode;
                        bodies[i].igrouptype = invProperty.iGroupType;
                    }
                }
            }
            
            return "ok";
        }

        /// <summary>
        /// 检查发货单号是否存在
        /// </summary>
        /// <param name="id">输出dlid</param>
        /// <returns></returns>
        public bool Exists(ref string idcheck)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
               DispatchList dl =db.Queryable<DispatchList>().Where(x => x.cDLCode == this.head.cdlcode).First();
                if (dl == null)
                {
                    idcheck = "";
                    return false; 
                }
                else
                {
                    return true;
                } 
            } 
        
        }

      
    }
}
